<template>
  <van-cell class="comment-item">
    <van-image
      slot="icon"
      round
      width="30"
      height="30"
      style="margin-right: 10px"
      :src="item.aut_photo"
    />
    <span style="color: #466b9d" slot="title">{{ item.aut_name }}</span>
    <div slot="label">
      <p style="color: #363636">{{ item.content }}</p>
      <p>
        <span style="margin-right: 10px">{{ item.pubdate | relativeTime }}</span>
        <van-button size="mini" type="default" @click="replyPopShow"
          >回复{{ item.reply_count }}</van-button
        >
      </p>
    </div>
    <van-button
      slot="right-icon"
      :icon="item.is_liking ? 'good-job' : 'good-job-o'"
      type="default"
      size="small"
      :class="{ liking: item.is_liking }"
      @click="tolike"
      :loading="commentLoading"
      >{{ item.like_count ? item.like_count : '赞' }}</van-button
    >
  </van-cell>
</template>

<script>
// 导入点赞评论api,和取消点赞评论的api
import { toLiking, toDisLiking } from '@/assets/api/comment'
// 导入store
import { mapState } from 'vuex'
// 导入通信组件
import eventHub from '@/assets/utils/communication'

export default {
  name: 'comment-item',
  props: {
    item: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      commentLoading: false
    }
  },
  methods: {
    // 点赞处理
    async tolike() {
      console.log(this.item)
      // 如果未登入返回提醒消息
      if (!this.user) {
        return this.$toast('请登入后在试')
      }
      this.commentLoading = true

      // 判断是点赞状态还是非点赞状态
      if (this.item.is_liking) {
        // 是点赞的状态，做取消点赞功能
        // 开启loading
        try {
          // 发起取消点赞的ajax请求
          //
          const { data: res } = await toDisLiking(this.item.com_id.toString())
        } catch {
          // 请求失败进行处理
          this.commentLoading = false
          return this.$toast('取消请求失败，请稍后重试')
        }

        this.$emit('toggleLiked', -1)
      } else {
        // 是非点赞状态，做点赞功能

        try {
          // 发起去点赞的请求
          // 开启loading
          const { data: res } = await toLiking(this.item.com_id.toString())
        } catch {
          // 对失败的请求进行处理
          this.commentLoading = false
          return this.$toast('点赞失败,请稍后再试')
        }
        this.$emit('toggleLiked', 1)
      }
      this.commentLoading = false
    },
    // 展示弹出层
    replyPopShow() {
      eventHub.$emit('showPop', this.item)
    }
  },
  computed: {
    ...mapState(['user'])
  }
}
</script>

<style lang="less" scoped>
.comment-item {
  .van-button {
    border: 0;
    &.liking {
      color: red;
    }
  }
}
</style>
